package com.usian.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.usian.common.aliyun.ScanTest;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.feign.ApArticleFeign;
import com.usian.feign.WemediaFeign;
import com.usian.mapper.SensitiveMapper;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.service.AdChannelService;
import com.usian.service.WemediaNewsAutoScanService;
import com.usian.utils.common.SensitiveWordUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private ScanTest scanTest;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ApArticleFeign apArticleFeign;
    @Autowired
    private AdChannelService adChannelService;
    @Autowired
    private SensitiveMapper sensitiveMapper;


    @Override
    //@GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {

        //1:校验参数
        if(id==null){
            return;
        }

        //2:根据id 查询 文章详情
        WmNews wmNews = wemediaFeign.findByNewId(id);
        if(wmNews==null){

            System.out.println("111111");
            return ;
        }
        //3：判断状态  4（人工审核通过） 8审核通过待发布   1 待审核
        if(wmNews.getStatus()==4){
            //人工审核通过，需要3张表入库
            this.saveArticle(wmNews);
            return ;
        }
        //判断状态是8 且发布时间<=当前时间   1573245423243423   yyyy-mm-dd hh:mm:ss
        if(wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            this.saveArticle(wmNews);
            return ;
        }

        //待审核
        if(wmNews.getStatus()==1){
            //4:审核 阿里云   敏感词审核
            //分离文本和图片（内容、封面）
            Map<String, Object> map = this.handleTextAndImages(wmNews);

            //审文本
            String content = map.get("content").toString();
            Map<String, Object> scanText = scanTest.scanText(content);
            if(!scanText.get("suggestion").equals("pass")){
                //文本不通过
                this.updateWmNewStatus(wmNews,(short)2,"文章内容阿里云审核失败");
                return;
            }
            //审图片
            List<String> imageList = (List<String>)map.get("image");
            for(String s :imageList){
                //s ==>  group1/M00/24/sdsdsdsdsdsdsds.jpg
                s =s.replace("http://192.168.58.138/","");
                String groupName = s.substring(0,s.indexOf("/"));
                String path = s.substring(s.indexOf("/")+1);
                System.out.println(groupName+"==="+path);
                try {
                    byte[] bytes = fastDFSClient.download(groupName, path);
                    Map<String, Object> scanImage = scanTest.scanImage(bytes);
                    if(!scanImage.get("suggestion").equals("pass")){
                        //文本不通过
                        this.updateWmNewStatus(wmNews,(short)2,"文章图片阿里云审核失败");
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //敏感词审核
            List<AdSensitive> allSensitive = sensitiveMapper.findAllSensitive();

            List<String> sensList = new ArrayList<>();
            for(AdSensitive adSensitive :allSensitive){
                sensList.add(adSensitive.getSensitives());
            }
            SensitiveWordUtil.initMap(sensList);
            Map<String, Integer> words = SensitiveWordUtil.matchWords(content);
            if(words.size()>0){
                //文本不通过
                this.updateWmNewStatus(wmNews,(short)2,"文章内容敏感词审核失败");
                return;
            }

            //审核通过，待发布
            if(wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                this.updateWmNewStatus(wmNews,(short)8,"审核通过待发布");
                return;
            }

            //审核通过已发布  维护3张表 //5：审核后数据入库
            this.saveArticle(wmNews);

        }

    }

    private Map<String,Object> handleTextAndImages(WmNews wmNews){
        //内容
        String content = wmNews.getContent();
        List<Map> mapList = JSONArray.parseArray(content, Map.class);

        StringBuilder stringBuilder =new StringBuilder();
        List<String> images =new ArrayList<>();

        for(Map map:mapList){
            if(map.get("type").equals("text")){
                //文本
                stringBuilder.append(map.get("value"));
            }
            if(map.get("type").equals("image")){
                //图片
                images.add(map.get("value").toString());
            }
        }

        //封面
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String,Object> result = new HashMap<>();
        result.put("content",stringBuilder);
        result.put("image",images);
        return result;
    }

    private void saveArticle(WmNews wmNews){
        //1:保存article主表
        ApArticle apArticle =new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        //处理一下作者信息  wmuser
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findByUserId(userId);
        if(wmUser!=null){
            ApAuthor apAuthor = apArticleFeign.findByName(wmUser.getName());
            if(apAuthor!=null){
                apArticle.setAuthorId(Long.valueOf(apAuthor.getId().toString()));
                apArticle.setAuthorName(apAuthor.getName());
            }
        }
        //维护频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getById(channelId);
        if(adChannel!=null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }
        ApArticle apArticle1 = apArticleFeign.saveApArticle(apArticle);

        //2 保存aparticleContent
        ApArticleContent apArticleContent =new ApArticleContent();
        apArticleContent.setArticleId(apArticle1.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleFeign.saveApArticleContent(apArticleContent);


        //3 保存aparticleConfig
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle1.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        apArticleFeign.saveApArticleConfig(apArticleConfig);

        //4:update wmnews status
        updateWmNewStatus(wmNews,(short) 9,"审核通过");

    }

    private void updateWmNewStatus(WmNews wmNews,short status, String msg){
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateNews(wmNews);
    }
}
